package com.usefullc.system.service.component.risk;

import com.usefullc.common.constants.SystemConstant;
import com.usefullc.common.exception.BizException;
import com.usefullc.system.service.AbstractService;
import com.usefullc.system.service.component.SystemConfigComponent;
import com.usefullc.system.service.interceptor.AspectProcess;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 防止重复提交，针对可配置的链接比如：支付完成，提现等
 * @author: Sampson
 * @date: 2022-06-19 15:31
 */
@Component
public class RepeatCheckAspectProcess extends AbstractService implements AspectProcess {

    @Autowired
    private RequestResComponent authComponent;

    @Autowired
    private RedisTemplate redisTemplate;

//    @Autowired
//    private ImgCodeComponent imgCodeComponent;

    @Autowired
    private SystemConfigComponent systemConfigComponent;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public void dealRepeatCheck(HttpServletRequest request){




    }

    @Override
    public void process(ProceedingJoinPoint joinPoint, HttpServletRequest request) {
        //获取随机种子
        String randomSeed = request.getHeader(SystemConstant.RANDOM_SEED);
        if (StringUtils.isEmpty(randomSeed)) {
            return;
        }
        Map<String, RequestResource> repeatUrlAuthResMap = authComponent.getRepeatUrlAuthResMap();
        String requestURI = request.getRequestURI();
        if (!repeatUrlAuthResMap.containsKey(requestURI)) {
            return;
        }
        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
        String cacheKey = deviceId + "_" + randomSeed +"_"+requestURI;
        logger.info("repeat url check cacheKey="+cacheKey);
        if (stringRedisTemplate.hasKey(cacheKey)) {
            throw new BizException("重复提交");
        }else{
            stringRedisTemplate.opsForValue().set(cacheKey,"1",5, TimeUnit.SECONDS);
        }
    }

    @Override
    public void clean() {

    }
}
